package com.ruixun.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruixun.entity.Role;
import com.ruixun.entity.User;
import com.ruixun.entity.UserRole;
import com.ruixun.mapper.RoleMapper;
import com.ruixun.mapper.UserMapper;
import com.ruixun.mapper.UserRoleMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * UserDetails服务实现类
 * @author ruixun
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserMapper userMapper;
    private final UserRoleMapper userRoleMapper;
    private final RoleMapper roleMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 根据用户名查询用户信息
        LambdaQueryWrapper<User> userWrapper = new LambdaQueryWrapper<>();
        userWrapper.eq(User::getLoginName, username)
                   .eq(User::getStatus, 1)
                   .eq(User::getDeleted, 0);

        User user = userMapper.selectOne(userWrapper);

        if (user == null) {
            log.error("用户不存在: {}", username);
            throw new UsernameNotFoundException("用户不存在");
        }

        // 查询用户角色
        List<SimpleGrantedAuthority> authorities = getUserAuthorities(user.getId());

        return new org.springframework.security.core.userdetails.User(
                user.getLoginName(),
                user.getPassword(),
                authorities
        );
    }

    /**
     * 获取用户权限
     */
    private List<SimpleGrantedAuthority> getUserAuthorities(Long userId) {
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();

        try {
            // 查询用户角色关联
            LambdaQueryWrapper<UserRole> userRoleWrapper = new LambdaQueryWrapper<>();
            userRoleWrapper.eq(UserRole::getUserId, userId);
            List<UserRole> userRoles = userRoleMapper.selectList(userRoleWrapper);

            if (!userRoles.isEmpty()) {
                // 查询角色信息
                List<Long> roleIds = userRoles.stream()
                        .map(UserRole::getRoleId)
                        .collect(Collectors.toList());

                LambdaQueryWrapper<Role> roleWrapper = new LambdaQueryWrapper<>();
                roleWrapper.in(Role::getId, roleIds)
                          .eq(Role::getDeleted, 0);
                List<Role> roles = roleMapper.selectList(roleWrapper);

                // 添加角色权限
                authorities.addAll(roles.stream()
                        .map(role -> new SimpleGrantedAuthority("ROLE_" + role.getValue()))
                        .collect(Collectors.toList()));
            }
        } catch (Exception e) {
            log.error("获取用户权限失败: {}", e.getMessage());
        }

        return authorities;
    }
}